package online.siwu.memorycards


import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.support.v7.app.AppCompatActivity
import android.view.KeyEvent
import android.view.View
import kotlinx.android.synthetic.main.activity_main.*
import java.io.File

@SuppressLint("SetTextI18n")
class MainActivity : AppCompatActivity() {

    var on = true
    val GD = GlobalData
    var timing = 0
    var whichCard = 1
    val handler = Handler()

    override fun onCreate(state: Bundle?) {
        super.onCreate(state)
        setContentView(R.layout.activity_main)
        loadFile()
        init()
    }

    private fun init() {
        btCard.setOnClickListener(oclCard)
        btNext.setOnClickListener(oclCard)
        bt110Code.setOnClickListener(oclCode)
        btAnswer.isEnabled = false
        btAnswer.setOnClickListener(oclAnswer)
        initTiming()
        showCard()
    }

    private fun initTiming() {
        tvTiming.text = "已用时 $timing 秒"
        timing++
        if (on)
            handler.postDelayed({ initTiming() }, 1000 * 1)
    }

    private val oclCard = View.OnClickListener {
        whichCard++
        if (whichCard > GD.exerNum) {
            on=false
            GD.jiTime = timing                              //记时间 放入GD
            btAnswer.setTextColor(bt110Code.textColors)
            btAnswer.setBackgroundResource(R.drawable.button_red)
            btAnswer.isEnabled = true
            btCard.visibility = View.INVISIBLE
            btNext.visibility = View.INVISIBLE
        } else
            showCard()
    }

    private val oclCode = View.OnClickListener {
        gotoActivity<CodeListActivity>(false)
    }

    private val oclAnswer = View.OnClickListener {
        gotoActivity<AnswerActivity>()
    }

    private fun loadFile() {
        val file = File(filesDir, "piles110.np")

        while (!GD.fileExists(file)) {
            GD.copy2Data(file, assets.open("piles110.np"))
        }
        GD.getCode110(file)
    }

    private fun showCard() {
        tvWhichCardYi.text = "现在是第【 $whichCard 】张，共${GD.exerNum}张！"
        btCard.text = GD.int2str110(GD.arrExer[whichCard - 1] as Int)
    }

    //====================================
    private var isExit: Boolean = false

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK)
            exitBy2Click() //调用双击退出函数
        return false
    }

    fun exitBy2Click() {
        val handler = Handler()
        if ((!isExit)) {
            isExit = true
            toast("再按一次退出APP")
            handler.postDelayed({ isExit = false }, 1000 * 2) //x秒后没按就取消
        } else {
            finish()
            System.exit(0)
        }
    }
}
